package com.shixi.shixitraining.shixitraining.http;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lzy.okgo.callback.AbsCallback;

import org.json.JSONObject;

import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by jeff on 2017/11/25.
 */

public abstract class JsonCallBack<T> extends AbsCallback<T> {

    private Class<T> clazz;
    private int result_code;
    private String result_message;
    private String responseBody;
    private Type type;
    private T t;

    public JsonCallBack() {
    }

    public JsonCallBack(Type type) {
        this.type = type;
    }

    public JsonCallBack(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void onSuccess(com.lzy.okgo.model.Response<T> response) {
        onParseSuccess(responseBody, result_code, result_message, t);
    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        t = null;
        responseBody = body.string();
        JSONObject jsonObject = new JSONObject(responseBody);
        result_code = jsonObject.getInt("result_code");
        result_message = jsonObject.getString("result_message");
        if (result_code == 1) {
            String data = jsonObject.getString("data");
            if (type != null) t = new Gson().fromJson(data, type);
            if (clazz != null) t = JSON.parseObject(data, clazz);
        }
        return t;
    }

    public abstract void onParseSuccess(String response, int code, String msg, T data);


}
